package com.tang.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tang.common.redis.AuthKeyBuilder;
import com.tang.component.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;


/**
 * 网关鉴权拦截器
 *
 * @author Tang
 * @date 2024/2/13 11:24
 **/
@Component
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        //返回此loginId拥有的权限列表
        String permissionKey = AuthKeyBuilder.getPermissionKey(loginId.toString());
        return getAuthList(permissionKey);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        String roleKey = AuthKeyBuilder.getRoleKey(loginId.toString());
        return getAuthList(roleKey);
    }

    private List<String> getAuthList(String key) {
        String authValue = redisUtil.get(key);
        //如果是数据为空
        if (StringUtils.isBlank(authValue)) {
            return Collections.emptyList();
        }
        //将json数据转为List
        Type type = new TypeToken<List<String>>() {
        }.getType();
        return new Gson().fromJson(authValue, type);
    }

}
